package com.zyp.weibo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class UploadController {
    @RequestMapping("/upload")
    //MultipartFile 用来接收传递过来的文件信息
    public String upload(MultipartFile picFile) throws IOException {
        String fileName = picFile.getOriginalFilename();                    // filename = 常州新北区长江湿地构建“活水公园”，强化湿地水质净化功能.jpg
        String suffix = fileName.substring(fileName.lastIndexOf("."));  // substring(4)截取下标4后面的一段(包括4)；lastIndexOf(".")返回"."下标 ||  suffix = .jpg
        fileName = UUID.randomUUID()+suffix;                                // filename = d98691bc-b3b9-43dd-9837-1ea68eab9b4b.jpg
        String dirPath = "d:/files";                                        // dirPath = d:/files
        SimpleDateFormat f = new SimpleDateFormat("/yyyy/MM/dd/");  // f = /yyyy/MM/dd/
        String datePath = f.format(new Date());                             // datePath = /2023/05/24/
        File dirFile = new File(dirPath+datePath);                // dirFile = d:/files/2023/05/24/
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        picFile.transferTo(new File(dirPath+datePath+fileName));  // picFile保存到d:/files/2023/05/24/d98691bc-b3b9-43dd-9837-1ea68eab9b4b.jpg
        return datePath+fileName;                                           // return  /2023/05/24/d98691bc-b3b9-43dd-9837-1ea68eab9b4b.jpg
    }

    @RequestMapping("/remove")
    public void remove(String url) {                                        // url = /2023/05/24/d98691bc-b3b9-43dd-9837-1ea68eab9b4b.jpg   (就是上面return的内容)
        new File("d:/files"+url).delete();                        // d:/files/2023/05/24/d98691bc-b3b9-43dd-9837-1ea68eab9b4b.jpg (完整的绝对路径)
    }
}
